'use client'

import { useState, useEffect, useRef, Suspense } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { supabase } from '@/lib/supabase'
import ChatInput from '@/components/chat/ChatInput'
import MessageList from '@/components/chat/MessageList'
import MessageBubble from '@/components/chat/MessageBubble'
import HistoryDialog from '@/components/chat/HistoryDialog'
import { Message, ChatSession } from '@/types/chat'

// 通过Next.js API路由转发，避免CORS问题
const API_BASE_URL = '/api/chat/completions'

// 国际化文本配置
const i18n = {
  zh: {
    aiHealth: 'AI健康',
    newChat: '新增会话',
    history: '历史对话'
  },
  en: {
    aiHealth: 'AI Health',
    newChat: 'New Chat',
    history: 'Chat History'
  }
}

function ChatContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const [userId, setUserId] = useState<string>('')
  const [userInfo, setUserInfo] = useState<any>(null)
  const [healthInfo, setHealthInfo] = useState<any>(null)
  const [language, setLanguage] = useState<string>('ZH')
  const [uiLanguage, setUiLanguage] = useState<'zh' | 'en'>('zh')
  const [isDarkMode, setIsDarkMode] = useState(false)
  const [messages, setMessages] = useState<Message[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [chatId, setChatId] = useState<string>('')
  const [showHistory, setShowHistory] = useState(false)
  const [historyList, setHistoryList] = useState<any[]>([])
  const [historyLoading, setHistoryLoading] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const scrollContainerRef = useRef<HTMLDivElement>(null)
  const shouldAutoScrollRef = useRef<boolean>(true)

  // 从URL参数获取用户信息和初始化
  useEffect(() => {
    const userIdParam = searchParams.get('userId')
    
    // 检测系统语言
    const detectedLanguage = detectLanguage()
    setLanguage(detectedLanguage)

    // 检测暗黑模式
    detectDarkMode()

    // 生成或获取chatId
    const newChatId = searchParams.get('chatId') || `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    setChatId(newChatId)

    // 只有当 URL 中存在 userId 参数时，才获取用户信息和健康信息
    if (userIdParam) {
      setUserId(userIdParam)
      fetchUserInfo(userIdParam)
      fetchHealthInfo(userIdParam)
    }
  }, [searchParams])

  // 监听系统主题变化
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    
    const handleChange = (e: MediaQueryListEvent) => {
      setIsDarkMode(e.matches)
    }
    
    mediaQuery.addEventListener('change', handleChange)
    return () => mediaQuery.removeEventListener('change', handleChange)
  }, [])

  // 检测系统语言
  const detectLanguage = (): string => {
    // 检查浏览器语言设置
    const browserLang = navigator.language || (navigator as any).userLanguage || 'zh-CN'

    // 检查是否为中文环境
    const isZh = browserLang.startsWith('zh')
    
    // 设置UI语言
    setUiLanguage(isZh ? 'zh' : 'en')
    
    return isZh ? 'ZH' : 'EN'
  }

  // 检测暗黑模式
  const detectDarkMode = () => {
    // 检查系统主题偏好
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    setIsDarkMode(prefersDark)
  }
  
  // 获取国际化文本
  const t = i18n[uiLanguage]

  // 获取用户信息
  const fetchUserInfo = async (userId: string) => {
    try {
      const response = await fetch(`/api/users/${userId}`)
      if (response.ok) {
        const data = await response.json()
        if (data.success) {
          setUserInfo(data.data)
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 获取健康信息
  const fetchHealthInfo = async (userId: string) => {
    try {
      const response = await fetch(`/api/health/data-summary?userId=${userId}`)
      if (response.ok) {
        const data = await response.json()
        if (data.success) {
          setHealthInfo(data.data)
        }
      }
    } catch (error) {
      console.error('获取健康信息失败:', error)
    }
  }

  // 格式化用户信息为JSON对象
  const formatUserInfo = (userInfo: any): any => {
    if (!userInfo) return { error: '用户信息未加载' }

    const formattedInfo: any = {}

    if (userInfo.name) formattedInfo.name = userInfo.name
    if (userInfo.age) formattedInfo.age = userInfo.age
    if (userInfo.gender) {
      // gender=1是男性，gender=2是女性
      if (userInfo.gender === 1 || userInfo.gender === '1') {
        formattedInfo.gender = '男'
      } else if (userInfo.gender === 2 || userInfo.gender === '2') {
        formattedInfo.gender = '女'
      } else if (userInfo.gender === 'male') {
        formattedInfo.gender = '男'
      } else if (userInfo.gender === 'female') {
        formattedInfo.gender = '女'
      } else {
        formattedInfo.gender = '未知'
      }
    }
    if (userInfo.height) formattedInfo.height = `${userInfo.height}cm`
    if (userInfo.weight) formattedInfo.weight = `${userInfo.weight}kg`
    if (userInfo.city) formattedInfo.city = userInfo.city

    // 如果没有任何信息，返回错误对象
    if (Object.keys(formattedInfo).length === 0) {
      return { error: '用户信息不完整' }
    }

    return formattedInfo
  }

  // 格式化健康信息为文本描述
  const formatHealthInfo = (healthInfo: any): string => {
    if (!healthInfo) return '健康信息未加载'

    let description = '📊 近14天健康数据摘要：\n\n'

    // 睡眠数据
    const sleepDays = healthInfo.sleep.daily_total_sleep_duration.filter((v: number) => v > 0).length
    if (sleepDays > 0) {
      const totalSleep = healthInfo.sleep.daily_total_sleep_duration.reduce((a: number, b: number) => a + b, 0)
      const avgSleep = Math.round(totalSleep / sleepDays)
      const totalDeepSleep = healthInfo.sleep.daily_deep_sleep_duration.reduce((a: number, b: number) => a + b, 0)
      const avgDeepSleep = Math.round(totalDeepSleep / sleepDays)

      // 转换为小时单位的辅助函数
      const formatMinutesToHours = (minutes: number): string => {
        const hours = Math.floor(minutes / 60)
        const mins = minutes % 60
        if (hours > 0 && mins > 0) {
          return `${hours}小时${mins}分钟`
        } else if (hours > 0) {
          return `${hours}小时`
        } else {
          return `${mins}分钟`
        }
      }

      description += `😴 睡眠数据 (${sleepDays}天有记录):\n`
      description += `   平均睡眠时长: ${formatMinutesToHours(avgSleep)}\n`
      description += `   平均深度睡眠: ${formatMinutesToHours(avgDeepSleep)}\n`

      // 如果有今天的详细信息，显示详细的睡眠阶段
      if (healthInfo.sleep.todayDetails) {
        const today = healthInfo.sleep.todayDetails
        description += `   📅 今日睡眠详情:\n`
        description += `     总睡眠: ${formatMinutesToHours(today.totalSleep)}\n`
        description += `     深度睡眠: ${formatMinutesToHours(today.deepSleep)}\n`
        description += `     浅睡眠: ${formatMinutesToHours(today.lightSleep)}\n`
        description += `     REM睡眠: ${formatMinutesToHours(today.remSleep)}\n`
        description += `     清醒时长: ${formatMinutesToHours(today.awakeTime)}\n`
      }
      description += '\n'
    }

    // 心脏健康数据
    const heartDays = healthInfo.heart.daily_avg_hr.filter((v: number) => v > 0).length
    if (heartDays > 0) {
      const avgHR = Math.round(healthInfo.heart.daily_avg_hr.reduce((a: number, b: number) => a + b, 0) / heartDays)
      const maxHR = Math.max(...healthInfo.heart.daily_max_hr.filter((v: number) => v > 0))
      const minHR = Math.min(...healthInfo.heart.daily_min_hr.filter((v: number) => v > 0))
      const avgHRV = Math.round(healthInfo.heart.daily_hrv.reduce((a: number, b: number) => a + b, 0) / heartDays)

      description += `❤️ 心脏健康 (${heartDays}天有记录):\n`
      description += `   平均心率: ${avgHR} BPM\n`
      description += `   最高心率: ${maxHR} BPM\n`
      description += `   最低心率: ${minHR} BPM\n`
      description += `   平均HRV: ${avgHRV} ms\n\n`
    }

    // 活动数据
    const activityDays = healthInfo.activity.daily_step_count.filter((v: number) => v > 0).length
    if (activityDays > 0) {
      const totalSteps = healthInfo.activity.daily_step_count.reduce((a: number, b: number) => a + b, 0)
      const avgSteps = Math.round(totalSteps / activityDays)

      description += `🚶 活动数据 (${activityDays}天有记录):\n`
      description += `   平均步数: ${avgSteps.toLocaleString()} 步\n\n`
    }

    // 呼吸健康数据
    const respiratoryDays = healthInfo.respiratory.daily_avg_spo2.filter((v: number) => v > 0).length
    if (respiratoryDays > 0) {
      const avgSpO2 = Math.round(healthInfo.respiratory.daily_avg_spo2.reduce((a: number, b: number) => a + b, 0) / respiratoryDays * 100) / 100
      const minSpO2 = Math.min(...healthInfo.respiratory.daily_min_spo2.filter((v: number) => v > 0))
      const maxSpO2 = Math.max(...healthInfo.respiratory.daily_max_spo2.filter((v: number) => v > 0))

      description += `🫁 呼吸健康 (${respiratoryDays}天有记录):\n`
      description += `   平均血氧饱和度: ${avgSpO2}%\n`
      description += `   最低血氧饱和度: ${minSpO2}%\n`
      description += `   最高血氧饱和度: ${maxSpO2}%\n\n`
    }

    // 血糖数据
    if (healthInfo.blood_glucose.length > 0) {
      description += `🩸 血糖数据 (${healthInfo.blood_glucose.length}条记录):\n`
      healthInfo.blood_glucose.forEach((item: any, index: number) => {
        description += `   ${index + 1}. ${item.context}: ${item.reading} mmol/L (${new Date(item.timestamp).toLocaleDateString()})\n`
      })
      description += '\n'
    }

    // 血压数据
    if (healthInfo.blood_pressure.length > 0) {
      description += `🩺 血压数据 (${healthInfo.blood_pressure.length}条记录):\n`
      healthInfo.blood_pressure.forEach((item: any, index: number) => {
        description += `   ${index + 1}. ${item.systolic}/${item.diastolic} mmHg (${new Date(item.timestamp).toLocaleDateString()})\n`
      })
      description += '\n'
    }

    return description.trim() || '暂无健康数据记录'
  }

  // 处理返回按钮
  const handleGoBack = () => {
    router.back()
  }

  // 处理新建会话
  const handleNewChat = () => {
    const newChatId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    setChatId(newChatId)
    setMessages([])
    // 更新URL参数
    const newUrl = new URL(window.location.href)
    newUrl.searchParams.set('chatId', newChatId)
    window.history.replaceState({}, '', newUrl.toString())
  }

  // 处理显示历史对话
  const handleShowHistory = async () => {
    // 如果没有 userId，不显示历史对话
    if (!userId) {
      console.warn('未登录用户，无法查看历史对话')
      return
    }

    setShowHistory(true)
    setHistoryLoading(true)
    try {
      const response = await fetch('/api/chat/history', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: userId
        })
      })

      if (response.ok) {
        const data = await response.json()
        setHistoryList(data.data?.list || [])
      } else {
        console.error('获取历史对话失败')
      }
    } catch (error) {
      console.error('获取历史对话出错:', error)
    } finally {
      setHistoryLoading(false)
    }
  }

  // 处理选择历史对话
  const handleSelectChat = (selectedChatId: string) => {
    setShowHistory(false)
    setChatId(selectedChatId)
    setMessages([])
    // 更新URL参数
    const newUrl = new URL(window.location.href)
    newUrl.searchParams.set('chatId', selectedChatId)
    window.history.replaceState({}, '', newUrl.toString())
    // 加载该会话的历史消息
    loadChatHistory(selectedChatId)
  }

  // 加载会话历史消息
  const loadChatHistory = async (selectedChatId: string) => {
    try {
      const response = await fetch('https://fastgpt2.vertu.cn/api/core/chat/getPaginationRecords', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer fastgpt-jtu0gvLwjdc9DRnDvIUZ8SakESKkvG9rkplB0MsarrYMOubtMCU5e`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          appId: '6879bf05beb4723de9db803f',
          chatId: selectedChatId,
          offset: 0,
          pageSize: 50,
          loadCustomFeedbacks: true
        })
      })

      if (response.ok) {
        const data = await response.json()
        const historyMessages = data.data?.list || []

        // 转换历史消息格式为我们的消息格式
        const convertedMessages: Message[] = historyMessages.map((msg: any) => ({
          id: msg._id || msg.dataId,
          role: msg.obj === 'Human' ? 'user' : 'assistant',
          content: msg.value?.[0]?.text?.content || msg.value?.[0]?.content || '消息内容',
          timestamp: new Date()
        }))

        setMessages(convertedMessages)
      }
    } catch (error) {
      console.error('加载会话历史失败:', error)
    }
  }

  // 自动滚动到底部（立即滚动，用于流式响应）
  const scrollToBottom = (smooth: boolean = false) => {
    if (scrollContainerRef.current) {
      const scrollOptions: ScrollToOptions = {
        top: scrollContainerRef.current.scrollHeight,
        behavior: smooth ? 'smooth' : 'auto'
      }
      scrollContainerRef.current.scrollTo(scrollOptions)
    }
  }

  // 流式滚动（使用 requestAnimationFrame 实现平滑跟随）
  const scrollToBottomSmooth = () => {
    if (shouldAutoScrollRef.current && scrollContainerRef.current) {
      requestAnimationFrame(() => {
        scrollToBottom(false)
      })
    }
  }

  // 检测用户是否手动滚动
  useEffect(() => {
    const container = scrollContainerRef.current
    if (!container) return

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container
      // 如果用户滚动到距离底部 100px 以内，则认为应该自动滚动
      const isNearBottom = scrollHeight - scrollTop - clientHeight < 100
      shouldAutoScrollRef.current = isNearBottom
    }

    container.addEventListener('scroll', handleScroll)
    return () => container.removeEventListener('scroll', handleScroll)
  }, [])

  // 当消息变化时滚动到底部
  useEffect(() => {
    scrollToBottom(true)
  }, [messages])

  // 发送消息到AI
  const sendMessage = async (content: string, images: File[] = [], files: File[] = []) => {
    if ((!content.trim() && images.length === 0 && files.length === 0) || isLoading) {
      return
    }

    setIsLoading(true)

    try {
      // 上传媒体文件
      const uploadedImages = await uploadMediaFiles(images, 'image')
      const uploadedFiles = await uploadMediaFiles(files, 'file')

      // 构建消息内容
      const messageContent: any[] = []

      if (content.trim()) {
        messageContent.push({
          type: 'text',
          text: content.trim()
        })
      }

      // 添加图片消息
      uploadedImages.forEach(uploadedImage => {
        messageContent.push({
          type: 'image_url',
          image_url: {
            url: uploadedImage.url
          }
        })
      })

      // 添加文件消息
      uploadedFiles.forEach(uploadedFile => {
        messageContent.push({
          type: 'file_url',
          name: uploadedFile.name,
          url: uploadedFile.url
        })
      })

      // 如果没有任何内容，提前返回
      if (messageContent.length === 0) {
        setIsLoading(false)
        return
      }

      // 添加用户消息到界面
      const userMessage: Message = {
        id: Date.now().toString(),
        role: 'user',
        content: messageContent,
        timestamp: new Date()
      }
      setMessages(prev => [...prev, userMessage])

      // 调用AI API（通过Next.js API路由转发，避免CORS）
      const response = await fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          chatId: chatId || undefined,
          stream: true,
          detail: false,
          variables: {
            userinfo: formatUserInfo(userInfo),
            healthInfo: formatHealthInfo(healthInfo),
            language: language
          },
          messages: [
            {
              role: 'user',
              content: messageContent
            }
          ]
        })
      })

      if (!response.ok) {
        let errorText = '未知错误'
        try {
          errorText = await response.text()
        } catch (e) {
          // 如果响应体已被读取，忽略错误
        }
        throw new Error(`API请求失败: ${response.status} - ${errorText}`)
      }

      // 处理流式响应
      const reader = response.body?.getReader()
      const decoder = new TextDecoder()

      let aiMessageContent = ''
      const aiMessageId = (Date.now() + 1).toString()

      // 添加AI消息占位符
      const aiMessage: Message = {
        id: aiMessageId,
        role: 'assistant',
        content: aiMessageContent,
        timestamp: new Date()
      }
      setMessages(prev => [...prev, aiMessage])

      if (reader) {
        try {
          let buffer = ''
          let isFirstChunk = true  // 标记是否为第一个数据块
          
          while (true) {
            const { done, value } = await reader.read()
            if (done) break

            buffer += decoder.decode(value, { stream: true })
            const lines = buffer.split('\n')
            buffer = lines.pop() || ''

            for (const line of lines) {
              const trimmedLine = line.trim()
              if (trimmedLine.startsWith('data: ')) {
                try {
                  const dataStr = trimmedLine.slice(6)
                  if (dataStr === '[DONE]') continue

                  const data = JSON.parse(dataStr)
                  if (data.choices?.[0]?.delta?.content) {
                    // 收到第一个内容时，立即隐藏 loading
                    if (isFirstChunk) {
                      setIsLoading(false)
                      isFirstChunk = false
                    }
                    
                    aiMessageContent += data.choices[0].delta.content
                    // 更新AI消息内容
                    setMessages(prev => prev.map(msg =>
                      msg.id === aiMessageId
                        ? { ...msg, content: aiMessageContent }
                        : msg
                    ))
                    // 实时滚动到底部（流式响应时使用快速滚动）
                    scrollToBottomSmooth()
                  }
                } catch (e) {
                  console.warn('解析响应数据失败:', e)
                }
              }
            }
          }

          // 处理缓冲区中剩余的内容
          if (buffer.trim()) {
            const trimmedLine = buffer.trim()
            if (trimmedLine.startsWith('data: ')) {
              try {
                const dataStr = trimmedLine.slice(6)
                if (dataStr !== '[DONE]') {
                  const data = JSON.parse(dataStr)
                  if (data.choices?.[0]?.delta?.content) {
                    aiMessageContent += data.choices[0].delta.content
                    setMessages(prev => prev.map(msg =>
                      msg.id === aiMessageId
                        ? { ...msg, content: aiMessageContent }
                        : msg
                    ))
                  }
                }
              } catch (e) {
                console.warn('解析缓冲区数据失败:', e)
              }
            }
          }
        } finally {
          reader.releaseLock()
        }
      }

      // 保存会话记录（只有在有userId的情况下才保存）
      if (userId && chatId && content.trim()) {
        try {
          await fetch('/api/chat/sessions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              userId: parseInt(userId),
              chatId: chatId,
              lastMessage: content.trim()
            })
          })
        } catch (error) {
          console.error('保存会话记录失败:', error)
          // 不阻塞主流程，静默失败
        }
      }

    } catch (error) {
      console.error('发送消息失败:', error)
      // 添加错误消息
      const errorMessage: Message = {
        id: Date.now().toString(),
        role: 'assistant',
        content: `抱歉，发送消息时出现错误：${error instanceof Error ? error.message : '未知错误'}。请稍后重试。`,
        timestamp: new Date(),
        isError: true
      }
      setMessages(prev => [...prev, errorMessage])
    } finally {
      setIsLoading(false)
    }
  }

  // 上传媒体文件到Supabase
  const uploadMediaFiles = async (files: File[], type: 'image' | 'file'): Promise<Array<{name: string, url: string}>> => {
    const uploadedFiles: Array<{name: string, url: string}> = []

    for (const file of files) {
      try {
        // 检查文件大小限制 (10MB)
        if (file.size > 10 * 1024 * 1024) {
          console.warn(`文件 ${file.name} 过大，跳过上传`)
          continue
        }

        const fileExt = file.name.split('.').pop() || 'bin'
        const timestamp = Date.now()
        const randomId = Math.random().toString(36).substr(2, 9)
        const fileName = `${timestamp}_${randomId}.${fileExt}`
        const filePath = `metaself/${type === 'image' ? 'images' : 'files'}/${fileName}`

        const { data, error } = await supabase.storage
          .from('vertu-oss')
          .upload(filePath, file, {
            cacheControl: '3600',
            upsert: false
          })

        if (error) {
          console.error(`上传文件 ${file.name} 失败:`, error)
          // 显示上传失败提示
          const errorMessage: Message = {
            id: Date.now().toString(),
            role: 'assistant',
            content: `文件 ${file.name} 上传失败，请稍后重试。`,
            timestamp: new Date(),
            isError: true
          }
          setMessages(prev => [...prev, errorMessage])
          continue
        }

        const { data: { publicUrl } } = supabase.storage
          .from('vertu-oss')
          .getPublicUrl(filePath)

        uploadedFiles.push({
          name: file.name,
          url: publicUrl
        })

        console.log(`文件 ${file.name} 上传成功:`, publicUrl)
      } catch (error) {
        console.error(`上传文件 ${file.name} 时出错:`, error)
      }
    }

    return uploadedFiles
  }

  return (
    <div className={`flex flex-col h-screen ${isDarkMode ? 'bg-gray-900' : 'bg-gray-50'}`}>
      {/* 头部 - 固定在顶部 */}
      <div className={`${isDarkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'} border-b p-3 sm:p-4 flex-shrink-0`}>
        <div className="flex items-center justify-between max-w-4xl mx-auto">
          <div className="flex items-center">
            {/* 返回按钮 */}
            {/* <button
              onClick={handleGoBack}
              className={`mr-3 p-2 ${isDarkMode ? 'text-gray-400 hover:text-gray-100 hover:bg-gray-700' : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100'} rounded-lg transition-colors`}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
            </button> */}

            {/* AI健康标题 */}
            {/* <div className="flex items-center">
              <div className={`w-8 h-8 ${isDarkMode ? 'bg-gray-700' : 'bg-black'} rounded-full flex items-center justify-center mr-3`}>
                <svg className="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                </svg>
              </div>
              <h1 className={`text-lg sm:text-xl font-semibold ${isDarkMode ? 'text-gray-100' : 'text-gray-900'}`}>{t.aiHealth}</h1>
            </div> */}
          </div>

          {/* 右侧功能按钮 */}
          <div className="flex items-center space-x-2">
            {/* 新增会话按钮 */}
            <button
              onClick={handleNewChat}
              className={`p-2 ${isDarkMode ? 'text-gray-400 hover:text-gray-100 hover:bg-gray-700' : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100'} rounded-lg transition-colors`}
              title={t.newChat}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
            </button>

            {/* 历史对话按钮 */}
            <button
              onClick={handleShowHistory}
              className={`p-2 ${isDarkMode ? 'text-gray-400 hover:text-gray-100 hover:bg-gray-700' : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100'} rounded-lg transition-colors`}
              title={t.history}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      {/* 消息列表 - 可滚动区域 */}
      <div className="flex-1 min-h-0 relative">
        <div 
          ref={scrollContainerRef}
          className="h-full overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-transparent"
        >
          <MessageList 
            messages={messages}
            onQuickQuestion={(question) => sendMessage(question)}
            isDarkMode={isDarkMode}
          >
            <div className="p-3 sm:p-4 space-y-3 sm:space-y-4 max-w-4xl mx-auto">
              {messages.map((message) => (
                <MessageBubble key={message.id} message={message} isDarkMode={isDarkMode} />
              ))}
              
              {/* 加载气泡 - 显示在消息列表中 */}
              {isLoading && (
                <div className="flex justify-start">
                  <div className={`max-w-[85%] sm:max-w-xs lg:max-w-md px-4 py-3 rounded-2xl ${isDarkMode ? 'bg-gray-700' : 'bg-gray-100'}`}>
                    <div className="flex items-center space-x-2">
                      <div className={`w-2 h-2 ${isDarkMode ? 'bg-gray-400' : 'bg-gray-400'} rounded-full animate-bounce`}></div>
                      <div className={`w-2 h-2 ${isDarkMode ? 'bg-gray-400' : 'bg-gray-400'} rounded-full animate-bounce`} style={{ animationDelay: '0.1s' }}></div>
                      <div className={`w-2 h-2 ${isDarkMode ? 'bg-gray-400' : 'bg-gray-400'} rounded-full animate-bounce`} style={{ animationDelay: '0.2s' }}></div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </MessageList>
          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* 输入区域 - 固定在底部 */}
      <div className={`${isDarkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'} border-t p-3 sm:p-4 flex-shrink-0`}>
        <ChatInput
          onSendMessage={sendMessage}
          disabled={isLoading}
          userId={userId}
          onMessageSent={scrollToBottom}
          isDarkMode={isDarkMode}
        />
      </div>

      {/* 历史对话弹窗 */}
      <HistoryDialog
        isOpen={showHistory}
        onClose={() => setShowHistory(false)}
        historyList={historyList}
        loading={historyLoading}
        onSelectChat={handleSelectChat}
        isDarkMode={isDarkMode}
      />
    </div>
  )
}

// 导出包装组件，使用 Suspense 包裹
export default function ChatPage() {
  return (
    <Suspense fallback={
      <div className="flex items-center justify-center h-screen bg-gray-50">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    }>
      <ChatContent />
    </Suspense>
  )
}
